package com.id.supaclean.ui.sub

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.id.supaclean.ktx.dp
import com.id.supaclean.R

class FocusOnAdapter : RecyclerView.Adapter<FocusOnAdapter.ViewHolder>() {
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val textView = view as? TextView
    }

    class ItemInfo(val name: String, val focusOn: Boolean = false)

    private val items = mutableListOf<ItemInfo>()

    fun addItem(info: ItemInfo, index: Int = itemCount) {
        items.add(index, info)
        notifyItemInserted(index)
//        notifyItemRangeChanged(index, index + itemCount)
    }

    fun removeItem(name: String) {
        var index = -1
        for (i in 0 until items.size) {
            if (items[i].name == name) {
                index = i
                break
            }
        }
        if (index == -1) return

        items.removeAt(index)
        notifyItemRemoved(index)
        if (index != itemCount) {
            notifyItemRangeChanged(index, itemCount - index)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_focus_on_text, parent, false))
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = items[position]
        holder.textView?.text = item.name
        if (item.focusOn) {
            holder.textView?.setTextColor(Color.parseColor("#F7243E"))
            val drawable = ContextCompat.getDrawable(holder.itemView.context, R.drawable.ic_focus_on)?.apply {
                setBounds(0, 0, 14.dp, 14.dp)
            }
            holder.textView?.compoundDrawablePadding = 4.dp
            holder.textView?.setCompoundDrawables(null, null, drawable, null)
        } else {
            holder.textView?.setTextColor(Color.parseColor("#2E2E2E"))
            holder.textView?.setCompoundDrawables(null, null, null, null)
        }
    }

    override fun getItemCount(): Int = items.size
}